package com.cmdi.auth.resource;

import com.alibaba.fastjson.JSONObject;
import com.cmdi.constant.CodeConstants;
import com.cmdi.constant.SecurityConstants;
import com.cmdi.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @Description: ResourceServerConfig
 * @Author: gaozb
 */
@Slf4j
@Configuration
@Component
@RefreshScope
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Value("${ignoreauth.urls:/swagger-ui.html}")
    private Set<String> noRequireTokenUris;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId(SecurityConstants.RESOURCE_ID)
                .tokenStore(tokenStore()).stateless(true)
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        R<HttpStatus> fail = R.fail(CodeConstants.ACCESS_DENIED_CODE, CodeConstants.ACCESS_DENIED_MESSAGE);
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        response.getWriter().write(JSONObject.toJSONString(fail));
                    }
                })
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        R<HttpStatus> fail = R.fail(CodeConstants.TOKEN_ERROR_CODE, CodeConstants.TOKEN_ERROR_MESSAGE);
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        response.getWriter().write(JSONObject.toJSONString(fail));
                    }
                })
        ;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //swagger相关全部放行
        noRequireTokenUris.add("/v2/api-docs");
        noRequireTokenUris.add("/swagger-resources/configuration/ui");
        noRequireTokenUris.add("/swagger-resources");
        noRequireTokenUris.add("/swagger-resources/configuration/security");
        noRequireTokenUris.add("/webjars/**");
        noRequireTokenUris.add("/swagger-ui.html");
        //druid相关全部放行
        noRequireTokenUris.add("/druid/**");

        log.info("noRequireTokenUris: {}", noRequireTokenUris);

        String[] passUrls = noRequireTokenUris.toArray(new String[noRequireTokenUris.size()]);
        http.csrf().disable()
                .sessionManagement().disable()
                .authorizeRequests()
                .antMatchers(passUrls).permitAll()
                .anyRequest().authenticated()
                .and().headers().cacheControl();
    }
    /**
     * 令牌存储方式，此处为jwt
     * 使用对称加密
     **/
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(SecurityConstants.SIGNINE_KEY);
        return jwtAccessTokenConverter;
    }
}